import 'dart:convert';
import "dart:io";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/user/api.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:dio/dio.dart";
import 'package:flutter/material.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/widgets/menu_block.dart';
import 'package:ct_pa_majordomo/utils/storage.dart';
import "package:flutter_easyloading/flutter_easyloading.dart";
import 'package:image_picker/image_picker.dart';

class Profile extends StatefulWidget {
  const Profile({super.key});

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  late Map _user;
  final ImagePicker _picker = ImagePicker();
  XFile? _imageFile;

  @override
  void initState() {
    String info = storage.getString("info") ?? "";
    _user = jsonDecode(info);
    super.initState();
  }

  void _updateUserInfo() {
    String info = jsonEncode(_user);
    storage.setString("info", info);
    setState(() {});
  }

  // 图片上传
  Future<void> _uploadImage() async {
    if (_imageFile == null) {
      throw Exception('No image selected');
    }
    EasyLoading.show();

    final file = File(_imageFile!.path);

    // 检查文件大小是否超过5M
    final sizeInMB = Utils.getFileSizeInMB(file);
    if (sizeInMB > 5) {
      EasyLoading.showToast("请上传小于5M的图片");
      return;
    }

    print('Starting image compression');
    File compressedFile;
    try {
      // 压缩图片至1M以下
      compressedFile = await Utils.compressImage(
        file,
        targetSizeInMB: 1.0,
        maxWidth: 1024,
        maxHeight: 1024,
      );
    } catch (e) {
      print('Compression error: $e');
      EasyLoading.showError("图片压缩失败，请选择其他图片");
      return;
    }

    final finalSize = Utils.getFileSizeInMB(compressedFile);
    print('Final file size: ${finalSize.toStringAsFixed(2)}MB');

    FormData formData = FormData();
    formData.files.add(MapEntry("file", await MultipartFile.fromFile(compressedFile.path, filename: _imageFile!.name)));
    Map res = await commonApi.upload(formData);
    await userApi.updateProfile({"avatar": res["data"]["url"]});
    EasyLoading.showSuccess("上传成功");
    setState(() {
      _user["avatar"] = res["data"]["url"];
    });
    _updateUserInfo();
    print("图片信息：$res");
  }

  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? image = await _picker.pickImage(source: source);
      if (image != null) {
        // TODO: 实现图片上传逻辑
        _imageFile = image;
        _uploadImage();
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  void _showImagePicker() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Wrap(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('从相册选择'),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.gallery);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  void _showNicknameDialog() {
    String newNickname = _user["nickName"];
    taiDialog(
      context: context,
      title: "修改昵称",
      child: TextField(
        controller: TextEditingController(text: newNickname),
        onChanged: (value) => newNickname = value,
        decoration: const InputDecoration(
          hintText: "请输入新昵称",
        ),
      ),
      onConfirm: (taiContext) async {
        if (newNickname.isNotEmpty) {
          try {
            await userApi.updateProfile({"nickName": newNickname});
            _user["nickName"] = newNickname;
            EasyLoading.showSuccess("修改成功");
            Stacker.pop();
            _updateUserInfo();
          } catch (e) {
            print(e);
          }
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('个人信息'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        children: [
          MenuBlock(
            items: [
              MenuBlockItem(
                prefix: const Text('头像'),
                text: '',
                suffix: GestureDetector(
                  onTap: _showImagePicker,
                  child: SizedBox(
                    width: 40,
                    height: 40,
                    child: _user["avatar"] != null && 
                           Utils.isNotEmpty(_user["avatar"]) &&
                           _user["avatar"].toString().startsWith("http")
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: Image.network(
                              _user["avatar"],
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return const CircleAvatar(
                                  child: Icon(Icons.person),
                                );
                              },
                            ),
                          )
                        : const CircleAvatar(
                            child: Icon(Icons.person),
                          ),
                  ),
                ),
              ),
              MenuBlockItem(
                prefix: const Text('昵称'),
                text: _user["nickName"],
                onTap: _showNicknameDialog,
              ),
            ],
          ),
        ],
      ),
    );
  }
} 